package com.ctrl.riveradministrator.mvp.view.activity.file_information;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ctrl.riveradministrator.R;
import com.ctrl.riveradministrator.base.BaseActivity;
import com.ctrl.riveradministrator.RaApplication;
import com.ctrl.riveradministrator.common.Constants;
import com.ctrl.riveradministrator.common.What;
import com.ctrl.riveradministrator.http.download.DownloadService;
import com.ctrl.riveradministrator.mvp.model.FileInfo;
import com.ctrl.riveradministrator.mvp.presenter.FileDownloadPresenter;

import java.io.File;
import java.util.List;

import es.voghdev.pdfviewpager.library.PDFViewPager;
import es.voghdev.pdfviewpager.library.RemotePDFViewPager;
import es.voghdev.pdfviewpager.library.adapter.PDFPagerAdapter;
import es.voghdev.pdfviewpager.library.remote.DownloadFile;
import es.voghdev.pdfviewpager.library.util.FileUtil;

public class FileActivity extends BaseActivity<FileDownloadPresenter> implements DownloadFile.Listener {

    //private WebView webView;
    private ProgressBar progressBar;
    private PDFViewPager pdfView;
    private RelativeLayout pdf_root;
    private FileInfo fileInfo;

    private Toolbar toolbar;
    private TextView titleTv, workTitle, workType, createBy, createTime, workRemark;
    private FloatingActionButton fab;
    private ImageView leftMenu;

    private RemotePDFViewPager remotePDFViewPager;
    private PDFPagerAdapter adapter;

    @Override
    protected void initParams(Bundle parms) {
        fileInfo = (FileInfo) getIntent().getSerializableExtra("fileInfo");
    }

    @Override
    protected int bindLayout() {
        return R.layout.activity_file;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void initView(View view) {
        toolbar = $(R.id.toolbar);
        titleTv = $(R.id.title_tv);
        leftMenu = $(R.id.left_iv);
        workTitle = $(R.id.title);
        workType = $(R.id.type);
        createBy = $(R.id.create_by);
        createTime = $(R.id.create_time);
        workRemark = $(R.id.remark);
        progressBar = $(R.id.pro);
        pdf_root = $(R.id.remote_pdf_root);
        fab = $(R.id.fab);
        /*
         * 设置toolbar
         * */
        toolbar.setTitleTextColor(Color.WHITE);
        toolbar.setTitle("");
        titleTv.setText(fileInfo.getTitle());
        leftMenu.setBackground(getDrawable(R.drawable.ic_chevron_left_24dp));

        final DownloadFile.Listener listener = this;
        remotePDFViewPager = new RemotePDFViewPager(this, Constants.BASE_URL_+fileInfo.getPath(), listener);
        remotePDFViewPager.setId(R.id.web);
    }

    @Override
    protected void doBusiness(Context mContext) {
        workTitle.setText(fileInfo.getTitle());
        workType.setText(fileInfo.getType());
        createBy.setText(fileInfo.getCreateBy());
        createTime.setText(fileInfo.getCreateTime());
        workRemark.setText(fileInfo.getRemark());
    }

    @Override
    protected void widgetClick(View view) {
        switch (view.getId()) {
            case R.id.left_iv:
                finish();
                break;
            case R.id.fab:
                // 进行文件下载
                if (isServiceRunning(DownloadService.class.getName())) {
                    Toast.makeText(this, "正在下载", Toast.LENGTH_SHORT).show();
                    return;
                }
                String downloadUrl = fileInfo.getPath();
                Intent intent = new Intent(this, DownloadService.class);
                Bundle bundle = new Bundle();
                bundle.putString("download_url", downloadUrl);
                bundle.putString("download_file", downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1));
                intent.putExtras(bundle);
                startService(intent);
                break;
        }
    }

    @Override
    protected void setListener() {
        leftMenu.setOnClickListener(this);
        fab.setOnClickListener(this);
    }

    @Override
    public void handleMessage(Message message, int what) {

    }

    @Override
    protected FileDownloadPresenter createPresenter() {
        return null;
    }

    /**
     * 打开文件，word、pdf
     *
     * @param context
     * @param f
     */
    private static void openFile(Context context, File f) {
        Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
        myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(f).toString());
        String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        myIntent.setDataAndType(Uri.fromFile(f), mimetype);
        context.startActivity(myIntent);

    }


    /**
     * 用来判断服务是否运行.
     *
     * @param className 判断的服务名字
     * @return true 在运行 false 不在运行
     */
    private boolean isServiceRunning(String className) {

        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) this
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(Integer.MAX_VALUE);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    @Override
    public void onSuccess(String url, String destinationPath) {
        progressBar.setVisibility(View.GONE);
        adapter = new PDFPagerAdapter(this, FileUtil.extractFileNameFromURL(url));
        remotePDFViewPager.setAdapter(adapter);
        pdf_root.removeAllViewsInLayout();
        pdf_root.addView(remotePDFViewPager, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onFailure(Exception e) {
        progressBar.setVisibility(View.GONE);
        Toast.makeText(FileActivity.this,"PDF获取失败",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onProgressUpdate(int progress, int total) {

    }

    public static class FileDownloadHandler extends android.os.Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case What.FILE_DOWNLOADING:
                    Log.d("file", "::f");
                    Toast.makeText(RaApplication.raApplication, "加载中...", Toast.LENGTH_SHORT).show();
                    break;
                case What.FILE_COMPLETED:
                    File file = (File) msg.obj;
                    openFile(RaApplication.raApplication, file);
                    break;
                case What.FILE_ERROR:
                    Toast.makeText(RaApplication.raApplication, "加载失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }

}
